
<template>
    <div class="page-container is-form">
        <a-spin :spinning="spinning">
            <a-form :layout="formLayout" :form="form">
                <a-form-item label="优惠券名称" v-bind="formItemLayout">
                    <a-input placeholder='请输入优惠券名称' v-decorator="['title',{rules: [{ required: true, message: '优惠券名称不能为空!' }]}]" style="width: 500px;"/>
                </a-form-item>
                <a-form-item label="优惠券类型" v-bind="formItemLayout">
                    <a-select v-decorator="['type',{rules:[{required:true,message:'请选择类型'}]}]" style="width:500px;">
                        <a-select-option v-for="item in couponTypeList" :key="item.id" :value="item.code">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="面值" v-bind="formItemLayout">
                    <a-input-number :precision="2" :min="0" style="width:200px" v-decorator="['amount',{rules: [{ required: true, message: '面值不能为空!'}]}]" />
                    <span class="default_tips tips_left">元</span>
                </a-form-item>
                <a-form-item label="是否限制订单金额" v-bind="formItemLayout" >
                    <a-radio-group v-decorator="['isFull',{rules: [{ required: true, message: '请选择是否限制订单金额!' }]}]">
                        <a-radio :value="true">是</a-radio>
                        <a-radio :value="false">否</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :wrapperCol="{span:18,offset:5}" v-show="form.getFieldValue('isFull')">
                    <span class="default_tips tips_right">满</span>
                    <a-input-number :precision="2" :min="0" style="width:200px" v-decorator="['fullAmount',{rules: [{ required: true, message: '订单金额不能为空!'}]}]"/>
                    <span class="default_tips tips_left">元可用</span>
                </a-form-item>
                <a-form-item label="可使用商品" v-bind="formItemLayout">
                    <a-radio-group  v-decorator="['userScope',{rules: [{ required: true, message: '请选择可使用商品!'}]}]">
                        <a-radio value="ALL" @click="onChangeAll">全店通用</a-radio>
                        <a-radio value="TYPE" @click="onChangeGoodsType">指定分类</a-radio>
                         <a-radio value="GOODS" @click="onChangeGoods">指定商品</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label='指定分类' v-bind="formItemLayout" v-show="form.getFieldValue('userScope') == 'TYPE'" >
                    <a-input style="width: 500px;" readonly @click="goodsTypeVisible = true" v-model="selectedType.name"></a-input>
                    <a-input type="hidden" v-decorator="['goodsTypeId',{rules: [{ required: true, message: '请选择指定分类!'}]}]"></a-input>
                </a-form-item>
                <a-form-item label='指定商品' v-bind="formItemLayout" v-show="form.getFieldValue('userScope') == 'GOODS'">
                    <a-input style="width: 500px;" readonly @click="goodsVisible = true" v-model="selectedGoods.name"></a-input>
                    <a-input type="hidden" v-decorator="['goodsId',{rules: [{ required: true, message: '请选择指定商品!'}]}]"></a-input>
                </a-form-item>
                <a-form-item label='是否限制发放总量'  v-bind="formItemLayout">
                    <a-radio-group  v-decorator="['isLimit',{rules: [{ required: true, message: '请选择是否限制发放总量!' }]}]">
                        <a-radio :value="true">是</a-radio>
                        <a-radio :value="false">否</a-radio>
                    </a-radio-group>
                </a-form-item>

                <a-form-item label='发放总量'  v-bind="formItemLayout" v-show="form.getFieldValue('isLimit')">
                    <a-input-number :min="1" style="width:200px" v-decorator="['num',{rules: [{ required: true, message: '发放总量不能为空!' }]}]">
                    </a-input-number><span class="default_tips tips_left">张</span>
                </a-form-item>

                <a-form-item label='是否永久有效'  v-bind="formItemLayout">
                    <a-radio-group  v-decorator="['isForever',{rules: [{ required: true, message: '请选择是否永久有效!' }]}]">
                        <a-radio :value="true">是</a-radio>
                        <a-radio :value="false">否</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label='生效时间'  v-bind="formItemLayout"  v-show="!form.getFieldValue('isForever')">
                    <a-date-picker v-decorator="['startDate',{rules: [{ required: true, message: '请选择生效时间!' }]}]"
                                   format="YYYY-MM-DD HH:mm:ss" :showTime="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
                </a-form-item>

                <a-form-item label='过期时间'  v-bind="formItemLayout"  v-show="!form.getFieldValue('isForever')">
                    <a-date-picker v-decorator="['endDate',{rules: [{ required: true, message: '请选择过期时间!' }]}]"
                                   format="YYYY-MM-DD HH:mm:ss" :showTime="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
                </a-form-item>

                <a-form-item label='是否限制每人限领'  v-bind="formItemLayout">
                    <a-radio-group v-decorator="['isLimitReceive',{rules: [{ required: true, message: '请选择是否限制每人限领!' }]}]">
                        <a-radio :value="true">是</a-radio>
                        <a-radio :value="false">否</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label='每人限领张数' v-bind="formItemLayout" v-show="form.getFieldValue('isLimitReceive')">
                    <a-input-number :min="1" style="width:200px" v-decorator="['receiveNum',{rules: [{ required: true, message: '每人限领张数不能为空!' }]}]">
                    </a-input-number><span class="default_tips tips_left">张</span>
                </a-form-item>
                <a-form-item label='使用说明' v-bind="formItemLayout">
                    <a-textarea placeholder="请输入使用说明" :rows="4" v-decorator="['remark',{rules: [ {validator: checkRemarkLen,}]}]" style="width: 500px;"></a-textarea>
                </a-form-item>
                <a-form-item :wrapperCol="{span:18,offset:5}">
                    <a-button  type='primary'  :loading="btnLoading" @click="onSubmit">保 存</a-button>
                </a-form-item>
            </a-form>
        </a-spin>
        <a-modal title="选择商品" v-model="goodsVisible" :footer="null" width="800px" class="selection-modal">
            <select-goods-list :selected-key="selectedGoods.id" v-if="goodsVisible" @result="emitGoods"></select-goods-list>
        </a-modal>
        <a-modal title="选择商品分类" v-model="goodsTypeVisible" :footer="null" width="800px" class="selection-modal">
            <goods-type-list :selected-key="selectedType.id" v-if="goodsTypeVisible" @result="emitGoodsType"></goods-type-list>
        </a-modal>
    </div>
</template>

<script>
    import moment from 'moment';
    import {GoodsTypeList} from "./components";
    import {save,findDetail} from "../../api/coupon";
    import {findListByType} from "../../api/pubData";
    import SelectGoodsList from '../../components/SelectGoods/index'

    export default {
        name: "CouponAdd",
        data(){
            return {
                formLayout: 'horizontal',
                spinning: false,
                goodsVisible: false,
                goodsTypeVisible: false,
                coupon: {
                    userScope: 'ALL',
                    type: undefined,
                    isLimit: false,
                    isLimitReceive: true,
                    isForever: false,
                    isFull: true,
                    startDate: moment(),
                },
                couponTypeList:[],
                params: {
                    dataType:101,
                    id: 0
                },
                selectedType: {},
                selectedGoods: {},
                btnLoading: false,
            }
        },
        components:{ SelectGoodsList,GoodsTypeList},
        computed: {
            formItemLayout () {
                const { formLayout } = this
                return formLayout === 'horizontal' ? {
                    labelCol: { span:5},
                    wrapperCol: { span:18 },
                } : {}
            },
        },
        methods:{
            moment,
            onChangeAll(){
                this.selectedType = {}
                this.selectedGoods = {}
                this.form.setFieldsValue({'goodsId': null, 'goodsTypeId':null});
            },
            onChangeGoodsType(){
                this.selectedGoods = {}
                this.form.setFieldsValue({'goodsId': null});
                this.goodsTypeVisible = true;
            },
            onChangeGoods(){
                this.selectedType = {}
                this.form.setFieldsValue({'goodsTypeId': null});
                this.goodsVisible = true;
            },
            //选择分类完成
            emitGoodsType(r){
                this.selectedType = r;
                this.goodsTypeVisible = false;
                this.form.setFieldsValue({'goodsTypeId': r.id});
            },
            //选择商品完成
            emitGoods(r){
                this.selectedGoods = r;
                this.goodsVisible = false;
                this.form.setFieldsValue({'goodsId': r.id});
            },
            checkRemarkLen(rule, value, callback){
                if (value && value.length >200) {
                    callback('不能超过200字!')
                } else {
                    callback()
                }
            },
            onSubmit(){
                this.btnLoading = true;
                var valids = ['title','type','isFull','amount','userScope','isLimit','isLimitReceive','isForever','remark'];
                var isFull = this.form.getFieldValue('isFull');
                if(isFull == true){
                    valids.push('fullAmount');
                }
                var userScope = this.form.getFieldValue('userScope');
                if(userScope == 'TYPE'){
                    valids.push('goodsTypeId');
                }else if(userScope == 'GOODS'){
                    valids.push('goodsId');
                }
                var isLimit = this.form.getFieldValue('isLimit');
                if(isLimit == true){
                    valids.push('num');
                }
                var isLimitReceive = this.form.getFieldValue('isLimitReceive');
                if(isLimitReceive == true){
                    valids.push('receiveNum');
                }
                var isForever = this.form.getFieldValue('isForever');
                if(isForever == false){
                    valids.push('startDate','endDate');
                }
                this.form.validateFields(valids,(err,values) => {
                        if (!err) {
                            let data = {...this.coupon,...values}
                            if(!values.isForever){
                                data.startDate = moment(values.startDate).format('YYYY-MM-DD HH:mm:ss')
                                data.endDate = moment(values.endDate).format('YYYY-MM-DD HH:mm:ss')
                            }
                            this.onSave(data);
                        }else{
                            this.btnLoading = false;
                        }
                    },
                )
            },
            async onSave(data){
                this.spinning = true;
                let resp = await save(data);
                this.spinning = false;
                let _this = this;
                if(this.qUtil.validResp(resp)){
                    this.$success({title:'保存成功!',okText:'确定',
                        onOk(){_this.$router.push({name:'CouponList'});}
                    });
                }else{
                    this.$error({title:resp.msg,okText:'确定'});
                    this.bntLoading = false;
                }
            },
            async loadBaseData(){
                let resp = await findListByType(this.params.dataType)
                console.log("=====>",resp)
                if(this.qUtil.validResp(resp)){
                    this.couponTypeList = resp.data.dataList || []
                }
            },
            async onLoad(){
                if(this.params.id == 0) return false;
                let resp = await findDetail(this.params.id);
                if(this.qUtil.validResp(resp)){
                    this.coupon = resp.data.model;
                    if(this.coupon.isForever == false){
                        let startDate = moment(this.coupon.startDate);
                        let endDate = moment(this.coupon.endDate);
                        this.form.setFieldsValue({startDate,endDate});
                    }
                    const {title,type,isFull,fullAmount,amount,userScope,goodsId,goodsTypeId,isLimit,num,isLimitReceive,receiveNum,isForever,remark} = resp.data.model;
                    this.form.setFieldsValue({title,type,isFull,fullAmount,amount,userScope,goodsId,goodsTypeId,isLimit,num,isLimitReceive,receiveNum,isForever,remark});
                   if(this.coupon.userScope=='TYPE'){
                        this.selectedType = {id: this.coupon.goodsTypeId,name:this.coupon.goodsTypeName};
                   }else if(this.coupon.userScope=='GOODS'){
                       this.selectedGoods = {id: this.coupon.goodsId,name:this.coupon.goodsName};
                   }
                   console.log("--===?>",this.coupon)
                }
            }
        },
        mounted(){
            this.params.id = parseInt(this.$route.query.id) || 0;
            this.loadBaseData()
            if(this.params.id == 0){
                this.form.setFieldsValue(this.coupon);
            }else{
                this.onLoad();
            }
        },
        beforeCreate () {
            this.form = this.$form.createForm(this)
        },
    }
</script>

<style lang="scss">
 .selection-modal .ant-modal-body{
     padding:10px;
 }
</style>